package com.example.taskdispatcher.slice;

import com.example.taskdispatcher.ResourceTable;
import com.example.taskdispatcher.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.element.ShapeElement;
import ohos.app.dispatcher.Group;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.Revocable;
import ohos.app.dispatcher.task.TaskPriority;

import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnSync;
    private Button mBtnAsync;
    private ProgressBar mProgressbarIndeterminate;
    private Button mBtnDelay;
    private Button mBtnGroup;
    private Button mBtnBarrier;
    private Button mBtnApply;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mBtnSync = (Button) findComponentById(ResourceTable.Id_btn_sync);
        mBtnSync.setClickedListener(this);
        mBtnAsync = (Button) findComponentById(ResourceTable.Id_btn_async);
        mBtnAsync.setClickedListener(this);
        mBtnDelay = (Button) findComponentById(ResourceTable.Id_btn_delay);
        mBtnDelay.setClickedListener(this);
        mBtnGroup = (Button) findComponentById(ResourceTable.Id_btn_group);
        mBtnGroup.setClickedListener(this);
        mBtnBarrier = (Button) findComponentById(ResourceTable.Id_btn_barrier);
        mBtnBarrier.setClickedListener(this);
        mBtnApply = (Button) findComponentById(ResourceTable.Id_btn_apply);
        mBtnApply.setClickedListener(this);

        // 进度条
        mProgressbarIndeterminate = (ProgressBar) findComponentById(ResourceTable.Id_progressbar_indeterminate);
        mProgressbarIndeterminate.setIndeterminate(true);
        ShapeElement element = new ShapeElement();
        element.setBounds(0, 0, 50, 50);
        element.setRgbColor(new RgbColor(255, 0, 0));
        mProgressbarIndeterminate.setInfiniteModeElement(element);

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        // 【同步分发】按钮，实现同步分发功能
        if (component.getId() == ResourceTable.Id_btn_sync) {
            // 全局并行任务分发器
            TaskDispatcher dispatcher =
                    getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            Utils.log("主线程:" + Thread.currentThread().getName());
            // 同步分发任务1
            Utils.log("同步分发任务1!");
            dispatcher.syncDispatch(new Runnable() {
                @Override
                public void run() {
                    try {
                        Utils.log("执行任务1的线程:"
                                + Thread.currentThread().getName());
                        Thread.sleep(2000);
                        Utils.log("任务1完成!");
                    } catch (InterruptedException e) {
                        Utils.log("任务1失败!");
                    }
                }
            });
            // 同步分发任务2
            Utils.log("同步分发任务2!");
            dispatcher.syncDispatch(new Runnable() {
                @Override
                public void run() {
                    try {
                        Utils.log("执行任务2的线程:"
                                + Thread.currentThread().getName());
                        Thread.sleep(2000);
                        Utils.log("任务2完成!");
                    } catch (InterruptedException e) {
                        Utils.log("任务2失败!");
                    }
                }
            });
            Utils.log("同步分发任务3!");
            // 同步分发任务3
            dispatcher.syncDispatch(new Runnable() {
                @Override
                public void run() {
                    try {
                        Utils.log("执行任务3的线程:"
                                + Thread.currentThread().getName());
                        Thread.sleep(2000);
                        Utils.log("任务3完成!");
                    } catch (InterruptedException e) {
                        Utils.log("任务3失败!");
                    }
                }
            });
            Utils.log("完成!");
        }
        // 【异步分发】按钮，实现异步分发任务
        if (component.getId() == ResourceTable.Id_btn_async) {
            // 全局并行任务分发器
            TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            // 异步分发任务
            Revocable revocable = dispatcher.asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    try {
                        Utils.log("执行任务的线程:"
                                + Thread.currentThread().getName());
                        Thread.sleep(2000);
                        Utils.log("任务完成!");
                    } catch (InterruptedException e) {
                        Utils.log("任务失败!");
                    }
                }
            });
            Utils.log("当前线程继续执行代码!");
        }

        // 【异步延迟任务分发】按钮，实现异步延迟任务分发
        if (component.getId() == ResourceTable.Id_btn_delay) {
            // 全局并行任务分发器
            TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            // 异步延迟任务分发
            dispatcher.delayDispatch(() -> {
                Utils.log("任务开始!");
                try {
                    Thread.sleep(2000);
                    Utils.log("任务完成!");
                } catch (InterruptedException e) {
                    Utils.log("任务失败!");
                }
            }, 5000);
            Utils.log("当前线程继续执行代码!");
        }

        // 【分组任务分发】按钮，实现分组任务分发
        if (component.getId() == ResourceTable.Id_btn_group) {
            // 全局并行任务分发器
            TaskDispatcher dispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            // 创建任务组
            Group group = dispatcher.createDispatchGroup();
            // 将任务1加入任务组
            dispatcher.asyncGroupDispatch(group, new Runnable(){
                @Override
                public void run() {
                    Utils.log("任务1完成!");
                }
            });
            // 将任务2加入任务组
            dispatcher.asyncGroupDispatch(group, new Runnable(){
                @Override
                public void run() {
                    Utils.log("任务2完成!");
                }
            });
            // 在任务组中的所有任务执行完成后执行
            dispatcher.groupDispatchNotify(group, new Runnable(){
                @Override
                public void run() {
                    Utils.log("组任务全部完成!");
                }
            });
        }

        // 【屏蔽任务分发】按钮，实现屏蔽任务分发
        if (component.getId() == ResourceTable.Id_btn_barrier) {
            // 并行任务分发器
            TaskDispatcher dispatcher =
                    createParallelTaskDispatcher(
                            "Dispatcher",
                            TaskPriority.DEFAULT);
            // 创建任务组。
            Group group = dispatcher.createDispatchGroup();
            // 将任务加入任务组
            dispatcher.asyncGroupDispatch(group, () ->{
                ThreadSleep(1000);
                Utils.log("任务1-1完成!");
            });
            dispatcher.asyncGroupDispatch(group, () ->{
                ThreadSleep(500);
                Utils.log("任务1-2完成!");
            });
            dispatcher.asyncDispatchBarrier(() ->{
                Utils.log("屏蔽任务1完成!");
            });
            dispatcher.asyncGroupDispatch(group, () ->{
                ThreadSleep(1000);
                Utils.log("任务2-1完成!");
            });
            dispatcher.asyncGroupDispatch(group, () ->{
                ThreadSleep(2000);
                Utils.log("任务2-2完成!");
            });
            dispatcher.asyncDispatchBarrier(() ->{
                Utils.log("屏蔽任务2完成!");
            });
            Utils.log("任务分配完毕");
        }

        // 【多次任务分发】按钮，实现一次分发任务，多次执行
        if (component.getId() == ResourceTable.Id_btn_apply) {

            getGlobalTaskDispatcher(TaskPriority.DEFAULT).applyDispatch(new Consumer<Long>() {
                @Override
                public void accept(Long index) {
                    Utils.log("执行次数: " + (index + 1));
                }
            }, 10);

        }
    }

    /**
     * 线程暂停
     * @param ms 时间，单位毫秒
     */
    private static void ThreadSleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Utils.log("线程暂停失败!");
        }
    }
}
